/*
 * This file is part of the EasyLogger Library.
 *
 * Copyright (c) 2015, Armink, <armink.ztl@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * 'Software'), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * Function: Unified portable interface for EasyLogger with RTT/UART DMA support.
 * Platform: FreeRTOS + SEGGER RTT / UART DMA
 * Created on: 2015-04-28
 * Modified: Unified version supporting both RTT and UART DMA
 */

#include <elog.h>
#include <stdio.h>
#include "FreeRTOS.h"
#include "task.h"
#include "semphr.h"

// 根据宏定义包含不同的头文件
#ifdef ELOG_OUTPUT_RTT
    #include "SEGGER_RTT.h"
#elif defined(ELOG_OUTPUT_UART_DMA)
    #include "cmsis_os2.h"
    #include "usart.h"
    #include "bsp_rtc.h"
    #include "bsp_usart.h"
#else
    #error "Please define either ELOG_OUTPUT_RTT or ELOG_OUTPUT_UART_DMA"
#endif

// 互斥信号量，用于同步日志输出，保证多线程环境下的日志输出安全
static SemaphoreHandle_t LogMutexSemaphore = NULL;

// 如果启用异步输出，则创建相关的任务和信号量
#ifdef ELOG_ASYNC_OUTPUT_ENABLE
    // 异步输出任务句柄
    TaskHandle_t async_thread = NULL;
    // 日志输出二进制信号量，用于异步输出任务的同步
    static SemaphoreHandle_t LogBinarySemaphore = NULL;
    // 异步输出任务函数，在后台异步输出日志
    static void async_output(void *arg);
#endif

// 时间缓冲区
#ifdef ELOG_OUTPUT_RTT
    static char cur_system_time[16] = {0};
#elif defined(ELOG_OUTPUT_UART_DMA)
    static char elog_timer[16] = {0};
#endif

/**
 * @brief 初始化日志端口
 * 
 * 该函数负责初始化日志模块所需的资源，包括信号量、互斥锁和创建异步输出任务
 * 
 * @return ElogErrCode 返回日志模块初始化的结果状态
 */
ElogErrCode elog_port_init(void) {
    ElogErrCode result = ELOG_NO_ERR;

#ifdef ELOG_ASYNC_OUTPUT_ENABLE
    // 配置任务栈大小和优先级
    const uint16_t stack_depth_words = 1024 / sizeof(StackType_t);
    
    #ifdef ELOG_OUTPUT_RTT
        const UBaseType_t priority = tskIDLE_PRIORITY + 1;
    #elif defined(ELOG_OUTPUT_UART_DMA)
        const UBaseType_t priority = osPriorityLow;
    #endif
    
    // 创建二进制信号量，用于日志输出同步
    LogBinarySemaphore = xSemaphoreCreateBinary();
    if (NULL == LogBinarySemaphore) {
        result = ELOG_CREATE_SEM_FAIL;
        return result;
    }

    // 尝试创建异步输出任务
    if (pdPASS != xTaskCreate(
            async_output,
            "elog_async",
            stack_depth_words,
            NULL,
            priority,
            &async_thread)) {
        vSemaphoreDelete(LogBinarySemaphore);
        LogBinarySemaphore = NULL;
        result = ELOG_CREATE_TASK_FAIL;
        return result;
    }
#endif

    // 创建互斥信号量，保证日志输出的互斥性
    LogMutexSemaphore = xSemaphoreCreateMutex();
    if (NULL == LogMutexSemaphore) {
        result = ELOG_CREATE_SEM_FAIL;
        // 清理已创建的资源
#ifdef ELOG_ASYNC_OUTPUT_ENABLE
        if (async_thread != NULL) {
            vTaskDelete(async_thread);
            async_thread = NULL;
        }
        if (LogBinarySemaphore != NULL) {
            vSemaphoreDelete(LogBinarySemaphore);
            LogBinarySemaphore = NULL;
        }
#endif
        return result;
    }

    // 返回初始化结果
    return result;
}

/**
 * EasyLogger port deinitialize
 */
void elog_port_deinit(void) {
#ifdef ELOG_ASYNC_OUTPUT_ENABLE
    if (async_thread != NULL) {
        vTaskDelete(async_thread);
        async_thread = NULL;
    }
    
    if (LogBinarySemaphore != NULL) {
        vSemaphoreDelete(LogBinarySemaphore);
        LogBinarySemaphore = NULL;
    }
#endif

    if (LogMutexSemaphore != NULL) {
        vSemaphoreDelete(LogMutexSemaphore);
        LogMutexSemaphore = NULL;
    }
}

/**
 * EasyLogger port output function
 *
 * @param log output log
 * @param size log size
 */
void elog_port_output(const char *log, size_t size) {
#ifdef ELOG_OUTPUT_RTT
    // 使用 SEGGER RTT 输出
    SEGGER_RTT_Write(0, log, size);
#elif defined(ELOG_OUTPUT_UART_DMA)
    // 使用 UART DMA 输出
    HAL_UART_Transmit_DMA(&huart1, (const uint8_t*)log, size);
    // 等待 DMA 传输完成
    xSemaphoreTake(bsp_uart1_dma_sema, portMAX_DELAY);
#endif
}

/**
 * output lock
 */
void elog_port_output_lock(void) {
    if (xPortIsInsideInterrupt()) {
        /* Mutexes cannot be used in interrupt service routines. */
        return;
    }

    if (NULL != LogMutexSemaphore) {
        xSemaphoreTake(LogMutexSemaphore, portMAX_DELAY);
    }
}

/**
 * output unlock
 */
void elog_port_output_unlock(void) {
    if (xPortIsInsideInterrupt()) {
        /* Mutexes cannot be used in interrupt service routines. */
        return;
    }

    if (NULL != LogMutexSemaphore) {
        xSemaphoreGive(LogMutexSemaphore);
    }
}

/**
 * get current time interface
 *
 * @return current time
 */
const char *elog_port_get_time(void) {
#ifdef ELOG_OUTPUT_RTT
    // RTT 版本：返回系统节拍计数
    #if (INCLUDE_xTaskGetSchedulerState == 1)
    if (xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED) {
    #endif
        snprintf(cur_system_time, sizeof(cur_system_time), "tick:%010lu", xTaskGetTickCount());
    #if (INCLUDE_xTaskGetSchedulerState == 1)
    } else {
        strncpy(cur_system_time, "tick:0000000000", sizeof(cur_system_time) - 1);
    }
    #endif
    return cur_system_time;
    
#elif defined(ELOG_OUTPUT_UART_DMA)
    // UART DMA 版本：使用 RTC 获取实际时间
    bsp_rtc_GetSystemTime_Fmt(elog_timer);
    return elog_timer;
#endif
}

/**
 * get current process name interface
 *
 * @return current process name
 */
const char *elog_port_get_p_info(void) {
    return "";
}

/**
 * get current thread name interface
 *
 * @return current thread name
 */
const char *elog_port_get_t_info(void) {
#if (INCLUDE_xTaskGetSchedulerState == 1)
    if ((xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED) && 
        !xPortIsInsideInterrupt()) {
        return pcTaskGetName(xTaskGetCurrentTaskHandle());
    }
#endif
    return "";
}

#ifdef ELOG_ASYNC_OUTPUT_ENABLE
/**
 * async output implementation
 */
static void async_output(void *arg) {
    size_t get_log_size = 0;
    
    // 根据配置选择缓冲区大小
    #ifdef ELOG_ASYNC_LINE_OUTPUT
        static char poll_get_buf[ELOG_LINE_BUF_SIZE - 4];
    #else
        #ifdef ELOG_OUTPUT_UART_DMA
            static char poll_get_buf[ELOG_ASYNC_OUTPUT_BUF_SIZE - 4];
        #else
            static char poll_get_buf[ELOG_LINE_BUF_SIZE - 4];
        #endif
    #endif

    while (true) {
        /* waiting log */
        xSemaphoreTake(LogBinarySemaphore, portMAX_DELAY);
        
        /* polling gets and outputs the log */
        while (true) {
#ifdef ELOG_ASYNC_LINE_OUTPUT
            get_log_size = elog_async_get_line_log(poll_get_buf, sizeof(poll_get_buf));
#else
            get_log_size = elog_async_get_log(poll_get_buf, sizeof(poll_get_buf));
#endif
            if (get_log_size) {
                elog_port_output(poll_get_buf, get_log_size);
            } else {
                break;
            }
        }
    }
}

/**
 * wake up async output thread
 * This function should be called when new log is written to buffer
 */
void elog_async_output_notice(void) {
    if (LogBinarySemaphore != NULL) {
        BaseType_t xHigherPriorityTaskWoken = pdFALSE;
        
        if (xPortIsInsideInterrupt()) {
            xSemaphoreGiveFromISR(LogBinarySemaphore, &xHigherPriorityTaskWoken);
            portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
        } else {
            xSemaphoreGive(LogBinarySemaphore);
        }
    }
}

#endif /* ELOG_ASYNC_OUTPUT_ENABLE */